import AsyncStorage from '@react-native-community/async-storage'
import { Contacts } from '../../pages';
import { LOGIN_URL,USERINFOURL, FRIENDREQUEST, GETCONTACTS } from "../../service";
import { CURRENT_USER_CONFIG, CURRENT_USER_KEY } from '../../storage';
import { POST,GET } from '../../utils';
import { CONSUMER_CONFIG, INIT_USER_STATE, SET_CURRENT_USER, SET_FRIEND_LIST, SET_FRIEND_MAP, SET_USER_FRIEND_REQUEST } from '../actions';
import UserFriendStorage from '../../storage/userFriend'
import FriendStorage from '../../storage/user'
import { User } from 'realm';
import { ResetMessageStore } from './message';
import Socket from '../../socket'
import {themes} from '../../theme'

// 退出清除数据
export const ResetUserStore = async (dispatch)=>{
  await AsyncStorage.removeItem(CURRENT_USER_KEY);
  dispatch({
    type: INIT_USER_STATE,
    payload: {
      currentUser: {},
      currentUserConfig: {},
      friendMap: {},
      friendList: [],
      userFriendRequest: [],
      userFriendRequestCount: 0,
    }
  })
}

export const UserLogin = (payload) => {
  return async (dispatch) => {
    const { account, password } = payload;
    const res = await POST(LOGIN_URL, {token: 'qweqweqweq', data: {password: password, username: account}})
    alert(JSON.stringify(res))
    if(res.status==='ok') {
     await AsyncStorage.setItem(CURRENT_USER_KEY, JSON.stringify(res.data))
      const user_config = await AsyncStorage.getItem(CURRENT_USER_CONFIG(res.data.userId))
      if(!user_config){
      await  AsyncStorage.setItem(CURRENT_USER_CONFIG(res.data.userId), JSON.stringify({theme: 'light', userMode: 'normal'}))
      dispatch({type: SET_CURRENT_USER, payload: {currentUser: res.data, currentUserConfig: {theme: 'light', userMode: 'normal'}}})
      return {success: true}
      }
      dispatch({type: SET_CURRENT_USER, payload: {currentUser: res.data, currentUserConfig: JSON.parse(user_config)}})
      return {success: true}
    }
    return  {success: false}
  };
};

export const AutoLogin = (payload) => {
  return async (dispatch) => {
    const userStr = await AsyncStorage.getItem(CURRENT_USER_KEY)
    const user = userStr?JSON.parse(userStr): null
    if (!user){
      return {status: false, errmsg: '登录已失效'}
    }
    const user_config = await AsyncStorage.getItem(CURRENT_USER_CONFIG(user.userId))
    if(!user_config){
      dispatch({type: SET_CURRENT_USER, payload: {currentUser: user, currentUserConfig: {theme: 'light', userMode: 'normal'}}})
    }else{
      dispatch({type: SET_CURRENT_USER, payload: {currentUser: user,  currentUserConfig: JSON.parse(user_config)}})

    }
    // 获取用户信息
    const res = await GET(USERINFOURL, { token:  user.token})

    if(!res.id){
      return {status: false, errmsg: '请求失败'}
    }
    // alert(JSON.stringify(res))

    AsyncStorage.setItem(CURRENT_USER_KEY, JSON.stringify({...user, ...res.data}))
    dispatch({type: SET_CURRENT_USER, payload: {currentUser: {...user, ...res.data}}})
    return {status: true}
  }
}

export const RecoverUserInfoOnInit = (payload) => {
  return async (dispatch, getState) => {
    const { user } = getState()
    if(!user||!user.currentUser||!user.currentUser.userId){
      return
    }
    const friendList = await UserFriendStorage.getData(user.currentUser.userId)
    const allFriend = await FriendStorage.getAllFriend(user.currentUser.userId)
    if(friendList&&allFriend&&allFriend.length){
      const friendMap = {}
      allFriend.forEach(i=> friendMap[i.fid] = i)
      dispatch({type: SET_FRIEND_MAP, payload:{friendMap}})
      dispatch({type: SET_FRIEND_LIST, payload: {friendList}})

    }

  }
}
export const ConsumerConfig = (conf) => {
  return (disPatch, getState) => {
    const prevConfig = getState().user.currentUserConfig
    const currentUserConfig = {...prevConfig, ...conf}
 
    disPatch({type: CONSUMER_CONFIG, payload: {currentUserConfig}})
  }
}

export const InitUserFriendRequest = () => {
  return async(dispatch, getState) => {
    const {user} = getState()
    if(!user||!user.currentUser||!user.currentUser.userId){
      return
    }
    const res = await GET(FRIENDREQUEST, {token: user.currentUser.token})
    if(res.code === 200) {
      let userFriendRequestCount = 0
      res.data.forEach (item=> {
        item.agree===false && userFriendRequestCount++
      })
      dispatch({
        type: SET_USER_FRIEND_REQUEST,
        payload: {
          userFriendRequest: res.data,
          userFriendRequestCount}
      })
      return {success: true, msg: '好友请求数据获取成功'}
    }
    return {success: false, msg: '网络错误'}
  }
}
export const GetUserFriendList =() => {
  return async (disPatch, getState) => {
    const {user} = getState()
    if(!user||!user.currentUser||!user.currentUser.userId){
      return
    }
    
    const res = await GET(GETCONTACTS, {token: user.currentUser.token})
    if(res.code === 200) {
      const {data} = res
      // alert(JSON.stringify(data))
      const friendMap = {}
      // alert(JSON.stringify(data))
      const friendList = data.map(item=> {
        const id = item.friend.id
        friendMap[id] = ((item)=> {
          const {friend} = item
          const fid = friend.id
          const fname = friend.username
          delete friend.username
          delete friend.id
          delete item.friend
          const uid = item.user
          delete item.user
          return {...friend, fid, ...item, uid, fname}
        })(item)
        return id
      })
      if(friendList.length){
        UserFriendStorage.saveData(user.currentUser.userId, friendList)
        FriendStorage.saveFriendList(Object.values(friendMap))
        disPatch({type: SET_FRIEND_MAP, payload:  {friendMap}})
        disPatch({type: SET_FRIEND_LIST, payload:  {friendList}})
      }
      return {status: true, errmsg: 'friendListUpdated'}
    }
    return {status: false, errmsg: res.status}
  }
}
 
export const Logout = () => {
  return async (dispatch) => {
    if(Socket.chatSocket){
      Socket.chatSocket.close()

    }
    
      // await ResetUserStore(dispatch)
      // await ResetMessageStore(dispatch)
      return {success: true, msg: ''}
  }
}


const initialState = {
  currentUser: {},
  currentUserConfig:{theme: 'light', userMode: 'normal'},
  friendMap: {},
  friendList: [],
  userFriendRequest: [],
  userFriendRequestCount: 0,
};



export default (state = initialState, action) => {
  const { type, payload } = action;
  switch (type) {
    default: {
      return { ...state, ...payload };
    }
  }
};